﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using WXFramework;
using WXFramework.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace WXFramework.FormTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private CropMenu CropMenu { get; set; }

        private string token
        {
            get
            {
                if (CropTokenManager.CropId != tbx_CropWXId.Text || CropTokenManager.Secret != tbx_CropWXSecret.Text)
                {
                    CropTokenManager.CropId = tbx_CropWXId.Text;
                    CropTokenManager.Secret = tbx_CropWXSecret.Text;
                    CropTokenManager.GetNewToken();
                }
                return CropTokenManager.GetToken();
            }
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            tbx_CropWXEncodingAESKey.Text = ConfigurationSettings.AppSettings["CropWXEncodingAESKey"];
            tbx_CropWXId.Text = ConfigurationSettings.AppSettings["CropWXId"];
            tbx_CropWXSecret.Text = ConfigurationSettings.AppSettings["CropWXSecret"];
            tbx_CropWXToken.Text = ConfigurationSettings.AppSettings["CropWXToken"];
            dv_msgnews.DataSource = new List<CropArticle>();
            dv_mpnews.DataSource = new List<CropMpArticle>();
            CropMenu = new CropMenu();
            BindMenuButtons();
        }


        private void BindMenuButtons()
        {
            var buttons = new List<CropMenuButton>();
            CropMenu.button.ToList().ForEach(it =>
            {
                it.Level = 0;
                buttons.Add(it);
                it.sub_button.ToList().ForEach(
                    s =>
                    {
                        s.Level = 1;
                        buttons.Add(s);
                    });
            });
            dv_Menu.DataSource = null;
            dv_Menu.DataSource = buttons;
        }



        private void button1_Click(object sender, EventArgs e)
        {
            tbx_msg.Text = CropWXManager.GetDeprtmentList(token);
            var result = JsonConvert.DeserializeObject<WXGetDepListJsonResult>(tbx_msg.Text);
            dv_deps.DataSource = result.department;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                NewDepModel model = new NewDepModel { parentid = tbx_newdep_parentid.Text, name = tbx_newdep_depname.Text, order = tbx_newdep_parentorder.Text };
                tbx_msg.Text = CropWXManager.CreatDepartment(model, token);

            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                NewDepModel model = new NewDepModel
                {
                    id = int.Parse(tbx_editdep_depid.Text),
                    order = tbx_editdep_order.Text,
                    name = tbx_editdep_depname.Text,
                    parentid = tbx_editdep_parentid.Text,

                };
                tbx_msg.Text = CropWXManager.UpdateDepartment(model, token);
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }


        }

        private void dv_deps_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.DelDepartment(tbx_deldep_id.Text, token);
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {

                var depids = new List<int>();
                tbx_newuser_dep.Text.Split(',').ToList().ForEach(it => depids.Add(int.Parse(it)));

                WXUserInfo model = new WXUserInfo
                {
                    userid = tbx_newuser_userid.Text,
                    name = tbx_newuser_name.Text,
                    department = depids,
                    email = tbx_newuser_email.Text,
                    gender = int.Parse(tbx_newuser_gender.Text),
                    position = tbx_newuser_postion.Text,
                    mobile = tbx_newuser_mobile.Text,
                    tel = tbx_newuser_tel.Text,
                    weixinid = tbx_newuser_wxid.Text,
                };

                tbx_msg.Text = CropWXManager.CreateUser(model, token);

            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                var depids = new List<int>();
                tbx_newuser_dep.Text.Split(',').ToList().ForEach(it => depids.Add(int.Parse(it)));

                WXUserInfo model = new WXUserInfo
                {
                    userid = tbx_newuser_userid.Text,
                    name = tbx_newuser_name.Text,
                    department = depids,
                    email = tbx_newuser_email.Text,
                    gender = int.Parse(tbx_newuser_gender.Text),
                    position = tbx_newuser_postion.Text,
                    mobile = tbx_newuser_mobile.Text,
                    tel = tbx_newuser_tel.Text,
                    weixinid = tbx_newuser_wxid.Text,
                    enable = int.Parse(tbx_user_enable.Text),
                };

                tbx_msg.Text = CropWXManager.UpdateUser(model, token);
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }

        }

        private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.DelUser(tbx_newuser_userid.Text, token);
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.GetDepUserInfo(tbx_newuser_dep.Text, "1", "0", token);
                var result = JsonConvert.DeserializeObject<WXGetDepUsersInfoJsonResult>(tbx_msg.Text);
                dv_user_depusers.DataSource = result.userlist;

            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.GetUserInfo(tbx_newuser_userid.Text, token);
                var userinfo = JsonConvert.DeserializeObject<WXUserInfo>(tbx_msg.Text);
                tbx_newuser_userid.Text = userinfo.userid;
                tbx_newuser_name.Text = userinfo.name;
                tbx_newuser_dep.Text = string.Join(",", userinfo.department);
                tbx_newuser_email.Text = userinfo.email;
                tbx_newuser_gender.Text = userinfo.gender.ToString();
                tbx_newuser_postion.Text = userinfo.position;
                tbx_newuser_mobile.Text = userinfo.mobile;
                tbx_newuser_tel.Text = userinfo.tel;
                tbx_newuser_wxid.Text = userinfo.weixinid;
                tbx_user_enable.Text = userinfo.enable.ToString();
                tbx_user_status.Text = userinfo.status.ToString();

                pbx_user_avatar.Image = string.IsNullOrEmpty(userinfo.avatar) ? null : Image.FromStream(CropWXManager.GetUserAvatar(userinfo.avatar));
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.CreateTag(token,
                    new WXTag { tagname = tbx_tag_tagname.Text });

            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.UpdateTag(token,
                    new WXTag { tagname = tbx_tag_tagname.Text, tagid = tbx_tag_id.Text });
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.DelTag(token, tbx_tag_id.Text);
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button13_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.GetTagUsers(token, tbx_tag_id.Text);
                var result = JsonConvert.DeserializeObject<WXGetTagUserJsonResult>(tbx_msg.Text);
                dv_tagusers.DataSource = result.userlist;
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button14_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.AddTagUser(token,
                    new AddAndDelTagUserModel
                    {
                        tagid = tbx_tag_id.Text,
                        userlist = tbx_tag_userlist.Text.Split(',').ToList(),
                    });
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button16_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.DelTagUser(token,
                    new AddAndDelTagUserModel
                    {
                        tagid = tbx_tag_id.Text,
                        userlist = tbx_tag_userlist.Text.Split(',').ToList(),
                    });
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button15_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.GetTagList(token);
                var result = JsonConvert.DeserializeObject<WXGetTagListJsonResult>(tbx_msg.Text);
                dv_tags.DataSource = result.taglist;
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button17_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog op = new OpenFileDialog();
                op.ShowDialog();
                if (string.IsNullOrEmpty(op.FileName)) return;
                tbx_msg.Text = CropWXManager.UploadMediaFile(token, op.FileName);
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button18_Click(object sender, EventArgs e)
        {
            try
            {
                var result = CropWXManager.GetMediaFile(token, tbx_media_mediaid.Text);
                pbx_media.Image = Image.FromStream(result);
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button19_Click(object sender, EventArgs e)
        {
            try
            {
                var msg = new CropTextMsg
                {
                    touser = tbx_msg_touser.Text,
                    toparty = tbx_msg_toparty.Text,
                    totag = tbx_msg_totag.Text,
                    agentid = tbx_msg_agentid.Text,

                };
                msg.text.content = tbx_msg_text.Text;
                tbx_msg.Text = CropWXManager.SendMsg(token, msg);
            }
            catch (Exception ex)
            {

                tbx_msg.Text = ex.Message;
            }

        }

        private void button20_Click(object sender, EventArgs e)
        {
            try
            {
                var msg = new CropImageMsg
                {
                    touser = tbx_msg_touser.Text,
                    toparty = tbx_msg_toparty.Text,
                    totag = tbx_msg_totag.Text,
                    agentid = tbx_msg_agentid.Text,

                };
                msg.image.media_id = tbx_msg_mediaid.Text;
                tbx_msg.Text = CropWXManager.SendMsg(token, msg);
            }
            catch (Exception ex)
            {

                tbx_msg.Text = ex.Message;
            }
        }

        private void button23_Click(object sender, EventArgs e)
        {
            try
            {
                var msg = new CropFileMsg
                {
                    touser = tbx_msg_touser.Text,
                    toparty = tbx_msg_toparty.Text,
                    totag = tbx_msg_totag.Text,
                    agentid = tbx_msg_agentid.Text,

                };
                msg.file.media_id = tbx_msg_mediaid.Text;
                tbx_msg.Text = CropWXManager.SendMsg(token, msg);
            }
            catch (Exception ex)
            {

                tbx_msg.Text = ex.Message;
            }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            try
            {
                var msg = new CropVoiceMsg
                {
                    touser = tbx_msg_touser.Text,
                    toparty = tbx_msg_toparty.Text,
                    totag = tbx_msg_totag.Text,
                    agentid = tbx_msg_agentid.Text,

                };
                msg.voice.media_id = tbx_msg_mediaid.Text;
                tbx_msg.Text = CropWXManager.SendMsg(token, msg);
            }
            catch (Exception ex)
            {

                tbx_msg.Text = ex.Message;
            }
        }

        private void button22_Click(object sender, EventArgs e)
        {
            try
            {
                var msg = new CropVideoMsg
                {
                    touser = tbx_msg_touser.Text,
                    toparty = tbx_msg_toparty.Text,
                    totag = tbx_msg_totag.Text,
                    agentid = tbx_msg_agentid.Text,

                };
                msg.video.media_id = tbx_msg_mediaid.Text;
                msg.video.title = tbx_msg_title.Text;
                msg.video.description = tbx_msg_description.Text;
                tbx_msg.Text = CropWXManager.SendMsg(token, msg);
            }
            catch (Exception ex)
            {

                tbx_msg.Text = ex.Message;
            }
        }

        private void button24_Click(object sender, EventArgs e)
        {
            try
            {
                var msg = new CropNewsMsg
                {
                    touser = tbx_msg_touser.Text,
                    toparty = tbx_msg_toparty.Text,
                    totag = tbx_msg_totag.Text,
                    agentid = tbx_msg_agentid.Text,

                };
                msg.news.articles = dv_msgnews.DataSource as List<CropArticle>;
                tbx_msg.Text = CropWXManager.SendMsg(token, msg);
            }
            catch (Exception ex)
            {

                tbx_msg.Text = ex.Message;
            }
        }

        private void button25_Click(object sender, EventArgs e)
        {
            var atricles = dv_msgnews.DataSource as List<CropArticle>;

            atricles.Add(new CropArticle
            {
                picurl = tbx_msg_picurl.Text,
                url = tbx_msg_newsurl.Text,
                title = tbx_msg_newstitle.Text,
                description = tbx_msg_newsdescription.Text,
            });
            dv_msgnews.DataSource = null;
            dv_msgnews.DataSource = atricles;
        }

        private void button26_Click(object sender, EventArgs e)
        {
            var articles = dv_mpnews.DataSource as List<CropMpArticle>;

            articles.Add(new CropMpArticle
            {
                author = tbx_msg_mpauthor.Text,
                title = tbx_msg_mptitle.Text,
                content = tbx_msg_mpcontent.Text,
                content_source_url = tbx_msg_mpurl.Text,
                digest = tbx_msg_mpdigest.Text,
                show_cover_pic = tbx_msg_mpcpic.Text,
                thumb_media_id = tbx_msg_mpmediaid.Text,
            });
            dv_mpnews.DataSource = null;
            dv_mpnews.DataSource = articles;

        }

        private void button27_Click(object sender, EventArgs e)
        {
            try
            {
                var msg = new CropMpNewsMsg
                {
                    touser = tbx_msg_touser.Text,
                    toparty = tbx_msg_toparty.Text,
                    totag = tbx_msg_totag.Text,
                    agentid = tbx_msg_agentid.Text,

                };
                msg.mpnews.articles = dv_mpnews.DataSource as List<CropMpArticle>;
                tbx_msg.Text = CropWXManager.SendMsg(token, msg);
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button28_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(tbx_menu_name.Text)) throw new Exception("名称不能为空。");

                if (CropMenu.button.Any(it => it.name == tbx_menu_name.Text) || CropMenu.button.SelectMany(it => it.sub_button).Any(it => it.name == tbx_menu_name.Text))
                    throw new Exception("按钮名称不能重复。");


                if (string.IsNullOrEmpty(tbx_menu_parent.Text))
                {
                    if (CropMenu.button.Count() >= 3) throw new Exception("一级按钮不能超过3个。");
                    CropMenu.button.Add(new CropMenuButton
                    {
                        type = cmb_menu_type.Text,
                        key = tbx_menu_key.Text,
                        name = tbx_menu_name.Text,
                        url = tbx_menu_url.Text,
                        Level = 0,
                    });
                }
                else
                {
                    var btn = CropMenu.button.FirstOrDefault(it => it.name == tbx_menu_parent.Text);
                    if (btn == null) throw new Exception("找不到父级按钮。");
                    if (btn.sub_button.Count >= 5) throw new Exception("二级按钮不能超过5个。");
                    btn.sub_button.Add(new CropMenuButton
                    {
                        type = cmb_menu_type.Text,
                        key = tbx_menu_key.Text,
                        name = tbx_menu_name.Text,
                        url = tbx_menu_url.Text,
                        Level = 1,
                    });

                }
                BindMenuButtons();
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button29_Click(object sender, EventArgs e)
        {
        }

        private void button30_Click(object sender, EventArgs e)
        {
            try
            {
                var rows = dv_Menu.SelectedRows;
                var button = CropMenu.button.FirstOrDefault(it => it.name == rows[0].Cells[2].Value.ToString());
                if (button != null)
                {
                    CropMenu.button.Remove(button);
                }
                else
                {
                    foreach (var b in CropMenu.button)
                    {
                        button = b.sub_button.FirstOrDefault(it => it.name == rows[0].Cells[2].Value.ToString());
                        if (button != null)
                        {
                            b.sub_button.Remove(button);
                            break;
                        }
                    }



                }


                BindMenuButtons();
            }
            catch (Exception)
            {


            }

        }

        private void button31_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.GetMenuList(token, tbx_menu_agentid.Text);
                var jsonstr = tbx_msg.Text.Substring(tbx_msg.Text.IndexOf('{', 1));
                jsonstr = jsonstr.Substring(0, jsonstr.Length - 1);
                CropMenu = JsonConvert.DeserializeObject<CropMenu>(jsonstr);
                BindMenuButtons();
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }
        }

        private void button29_Click_1(object sender, EventArgs e)
        {

            try
            {
                tbx_msg.Text = CropWXManager.CreateMenu(token, tbx_menu_agentid.Text, CropMenu);
            }
            catch (Exception ex)
            {

                tbx_msg.Text = ex.Message;
            }
        }

        private void button32_Click(object sender, EventArgs e)
        {
            try
            {
                tbx_msg.Text = CropWXManager.DelMenu(token, tbx_menu_agentid.Text);
            }
            catch (Exception ex)
            {
                tbx_msg.Text = ex.Message;
            }

        }

        private void button33_Click(object sender, EventArgs e)
        {
            var repmsg = new ResponseTextMessage()
            {
                ToUserName = "all",
                Content = "test content",
                CreateTime = DateTime.Now.Ticks,
            };
            tbx_msg.Text = repmsg.Serializable();
        }

        private void button34_Click(object sender, EventArgs e)
        {
            tbx_msg.Text = HttpHelper.HttpPost(tbx_posturl.Text, tbx_postdata.Text);
        }
    }
}
